
import random
from datetime import datetime, timedelta
from typing import List, Dict
import requests
from models.article import Article
from database.database import SessionLocal

class ArticleGenerator:
    def __init__(self):
        self.topics = [
            "科技前沿", "生活妙招", "健康养生", "职场技能", "教育育儿",
            "美食探店", "旅游攻略", "数码评测", "时尚潮流", "汽车资讯",
            "房产家居", "情感故事", "创业故事", "财经分析", "体育热点"
        ]
        
        self.templates = {
            "科技前沿": {
                "title_templates": [
                    "震惊！{tech_company}发布{product}，{feature}功能太强大了",
                    "{year}年最值得期待的{tech_product}，{advantage}让人惊艳",
                    "深度解析：{tech_trend}将如何改变我们的生活？"
                ],
                "content_templates": [
                    "今天，{tech_company}正式发布了全新的{product}，这款产品最大的亮点就是{feature}...\n\n"
                    "从实际体验来看，{product}在{aspect}方面表现出色，{specific_data}...\n\n"
                    "业内人士分析认为，这款产品的发布将对{industry}产生{impact}的影响..."
                ]
            },
            "生活妙招": {
                "title_templates": [
                    "{problem}太烦人？教你一招{solution}，简单又实用",
                    "99%的人都不知道的{life_hack}，{benefit}效果惊人",
                    "实测有效！{method}让{item}焕然一新"
                ],
                "content_templates": [
                    "生活中，{problem}确实让人头疼。今天教大家一个简单的方法...\n\n"
                    "具体步骤如下：\n1. {step1}\n2. {step2}\n3. {step3}\n\n"
                    "经过{time_period}的测试，这个方法确实能够{benefit}..."
                ]
            },
            "健康养生": {
                "title_templates": [
                    "医生提醒：{habit}正在悄悄伤害你的{body_part}",
                    "{age}岁后必做的{health_check}，很多人忽视了",
                    "每天坚持{simple_action}，{health_benefit}效果看得见"
                ],
                "content_templates": [
                    "最近，{expert}提醒广大市民：{habit}可能会对{body_part}造成{harm}...\n\n"
                    "研究表明，{research_data}的人群更容易出现{health_issue}...\n\n"
                    "专家建议：{recommendation}，这样能够有效{benefit}..."
                ]
            }
        }
    
    def generate_article(self, topic: str = None) -> Dict[str, str]:
        """生成一篇原创文章"""
        if not topic:
            topic = random.choice(self.topics)
        
        template = self.templates.get(topic, self.templates["生活妙招"])
        
        # 生成标题
        title_template = random.choice(template["title_templates"])
        title = self._fill_template(title_template, topic)
        
        # 生成内容
        content_template = random.choice(template["content_templates"])
        content = self._fill_template(content_template, topic)
        
        # 生成摘要
        summary = content[:150] + "..." if len(content) > 150 else content
        
        # 生成标签
        tags = [topic, self._get_related_tag(topic), self._get_related_tag(topic)]
        
        return {
            "title": title,
            "content": content,
            "summary": summary,
            "tags": tags,
            "topic": topic
        }
    
    def _fill_template(self, template: str, topic: str) -> str:
        """填充模板变量"""
        placeholders = {
            "tech_company": ["华为", "小米", "苹果", "三星", "谷歌", "微软"],
            "product": ["智能手机", "平板电脑", "智能手表", "无线耳机", "笔记本电脑"],
            "feature": ["AI智能", "超长续航", "极速充电", "高清摄像", "5G网络"],
            "tech_trend": ["人工智能", "物联网", "区块链", "元宇宙", "量子计算"],
            "problem": ["厨房油污", "衣服褶皱", "手机卡顿", "房间异味", "鞋子发黄"],
            "solution": ["清洁神器", "除皱技巧", "优化方法", "除味妙招", "美白秘籍"],
            "habit": ["熬夜", "久坐", "不吃早餐", "过度用眼", "缺乏运动"],
            "body_part": ["肝脏", "颈椎", "胃部", "眼睛", "心血管"],
            "age": ["30", "35", "40", "45", "50"],
            "simple_action": ["喝水", "走路", "深呼吸", "伸展", "冥想"]
        }
        
        filled = template
        for key, values in placeholders.items():
            if "{" + key + "}" in filled:
                filled = filled.replace("{" + key + "}", random.choice(values))
        
        # 处理特殊变量
        filled = filled.replace("{year}", "2025")
        filled = filled.replace("{life_hack}", random.choice(["清洁技巧", "收纳方法", "生活窍门"]))
        
        return filled
    
    def _get_related_tag(self, topic: str) -> str:
        """获取相关标签"""
        related_tags = {
            "科技前沿": ["人工智能", "数码新品", "科技资讯"],
            "生活妙招": ["居家生活", "实用技巧", "生活百科"],
            "健康养生": ["健康科普", "养生知识", "医学常识"],
            "职场技能": ["职场提升", "办公技巧", "职业发展"],
            "教育育儿": ["育儿知识", "教育资讯", "亲子教育"],
            "美食探店": ["美食推荐", "餐厅打卡", "烹饪技巧"],
            "旅游攻略": ["旅游攻略", "景点推荐", "旅行日记"],
            "数码评测": ["产品评测", "数码科技", "使用体验"],
            "时尚潮流": ["时尚穿搭", "潮流资讯", "美妆护肤"],
            "汽车资讯": ["汽车评测", "新车发布", "用车知识"]
        }
        
        tags = related_tags.get(topic, ["热门话题", "生活分享"])
        return random.choice(tags)
    
    def generate_daily_articles(self, count: int = 3) -> List[Dict]:
        """生成每日文章"""
        articles = []
        selected_topics = random.sample(self.topics, min(count, len(self.topics)))
        
        for topic in selected_topics:
            article = self.generate_article(topic)
            articles.append(article)
        
        return articles
    
    def save_articles_to_db(self, articles: List[Dict]) -> List[int]:
        """保存文章到数据库"""
        db = SessionLocal()
        article_ids = []
        
        try:
            for article_data in articles:
                article = Article(
                    title=article_data["title"],
                    content=article_data["content"],
                    summary=article_data["summary"],
                    tags=article_data["tags"],
                    status="draft",
                    scheduled_time=datetime.now() + timedelta(hours=1)
                )
                db.add(article)
                db.commit()
                article_ids.append(article.id)
        except Exception as e:
            db.rollback()
            raise e
        finally:
            db.close()
        
        return article_ids
